package com.hqd.jjvm.jnative.misc;

import com.hqd.jjvm.jnative.JNativeRegistry;
import com.hqd.jjvm.rtda.JThread;
import com.hqd.jjvm.rtda.StackFrame;
import com.hqd.jjvm.rtda.heap.JClass;
import com.hqd.jjvm.rtda.heap.JMethod;
import com.hqd.jjvm.rtda.heap.classloader.JClassLoader;

import java.io.IOException;

public class JVMNativeRegistry extends JNativeRegistry {
    private static final JVMNativeRegistry instance = new JVMNativeRegistry();
    protected static final String CLASS_PATH = "sun/misc/VM";

    static {
        registry(CLASS_PATH, "initialize", "()V", JVMNativeRegistry::initialize);
    }

    private static void initialize(JThread jThread) {
        StackFrame stackFrame = jThread.getJvmStack().getTop();
        JClassLoader loader = stackFrame.getJClass().getLoader();
        try {
            JClass systemJClass = loader.loadJClass("java/lang/System");
            JMethod jMethod = systemJClass.getJMethod("initializeSystemClass", "()V");
            jThread.createStackFrame(jMethod);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static JVMNativeRegistry getInstance() {
        return instance;
    }
}
